package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.product.api.domain.SkuLockVo;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.SkuStockMapper;
import com.spzx.product.service.ISkuStockService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.product.vo.SkuStockVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品sku库存表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2024-11-12
 */
@Service
public class SkuStockServiceImpl extends ServiceImpl<SkuStockMapper, SkuStock> implements ISkuStockService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public SkuStockVo getSkuStock(Long skuId) {

        LambdaQueryWrapper<SkuStock> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SkuStock::getSkuId,skuId)
                .select(SkuStock::getAvailableNum,SkuStock::getSaleNum);
        SkuStock skuStock = baseMapper.selectOne(queryWrapper);

        SkuStockVo skuStockVo = new SkuStockVo();
        skuStockVo.setAvailableNum(skuStock.getAvailableNum());
        skuStockVo.setSaleNum(skuStock.getSaleNum());
        skuStockVo.setSkuId(skuId);
        return skuStockVo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String checkAndLock(String orderNo, List<SkuLockVo> skuLockVoList) {

        for (SkuLockVo skuLockVo : skuLockVoList) {
            SkuStock skuStock = baseMapper.check(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            if (skuStock==null){
                skuLockVo.setHaveStock(false);
            }else {
                skuLockVo.setHaveStock(true);
            }
        }
        //检查库存不足的商品，只要有一个库存不足，则组装错误信息
        if (skuLockVoList.stream().anyMatch(skuLockVo -> !skuLockVo.isHaveStock())){
            //过滤出库存不足的商品
            List<SkuLockVo> noStockList = skuLockVoList.stream().filter(item->!item.isHaveStock())
                    .collect(Collectors.toList());

            //组装错误提示
            StringBuffer errorMsg = new StringBuffer();
            for (SkuLockVo skuLockVo : noStockList) {
                //查询现有库存
                Integer num = baseMapper.selectById(skuLockVo.getSkuId()).getAvailableNum();
                errorMsg.append(skuLockVo.getSkuName())
                        .append("库存不足，剩余库存：")
                        .append(num)
                        .append("；");
            }
            return errorMsg.toString();

        }else {
            //锁定库存
            for (SkuLockVo skuLockVo : skuLockVoList) {
                baseMapper.lock(skuLockVo.getSkuId(),skuLockVo.getSkuNum());
            }
            //如果成功锁定库存，则将库存信息缓存到redis中，方便后续做释放库存或扣减库存的操作
            String dataKey = "sku:lock:data:" + orderNo;
            this.redisTemplate.opsForValue().set(dataKey, skuLockVoList);
            return "success";
        }

    }

    @Override
    public void unlock(String orderNo) {

        //幂等性
        String key = "sku:unlock:" + orderNo;
        Boolean isFirst =redisTemplate.opsForValue().setIfAbsent(key, orderNo,10, TimeUnit.MINUTES);
        if(!isFirst) return;

        String dataKey = "sku:lock:data:" + orderNo;
        List<SkuLockVo> skuLockVoList = (List<SkuLockVo>)this.redisTemplate.opsForValue().get(dataKey);

        if (!CollectionUtils.isEmpty(skuLockVoList)){
            for (SkuLockVo skuLockVo : skuLockVoList) {
                baseMapper.unlock(skuLockVo.getSkuId(),skuLockVo.getSkuNum());
            }
        }

    }
}
